package com.xsr.blog.demo.javablacklistdesign.Interceptor;

import com.xsr.blog.demo.javablacklistdesign.Mbean.BlacklistMBean;
import com.xsr.blog.demo.javablacklistdesign.service.IpService;
import com.xsr.blog.demo.javablacklistdesign.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author：xsr
 * @Date：2024/1/28 21:21
 * 自定义黑名单ip拦截器，用于第一层处理非法ip
 */
@Component
public class BlackListInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(BlackListInterceptor.class);
    @Autowired
    private IpService ipService;
    @Autowired
    private BlacklistMBean blacklistMBean;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestIp = RequestUtil.getRequestIp(request);
        logger.info("拦截器：检查ip："+requestIp);
        //ipservice ：检查ip是否合法
//        if (ipService.isBlacklisted(requestIp)) {
//            logger.info("拦截器：拦截到非法ip："+requestIp);
//            return false;
//        }
//        return true;

        //BlackListMbean：检查ip是否合法

        if (blacklistMBean.shouldBlock(requestIp)) {
            logger.info("拦截器：拦截到非法ip："+requestIp);
            return false;

        }
        return true;

    }
}
